<?php

namespace App\Http\Controllers\Auth;
use DB;
use App\User;
use App\Log;
use Validator;
use Auth;
use App\Http\Controllers\Controller;
use App\Repositories\UserRepository;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\Http\Request;

class AuthController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Registration & Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users, as well as the
    | authentication of existing users. By default, this controller uses
    | a simple trait to add these behaviors. Why don't you explore it?
    |
    */

    use AuthenticatesAndRegistersUsers, ThrottlesLogins;

    /**
     * Where to redirect users after login / registration.
     *
     * @var string
     */
    protected $redirectTo = '/';

    protected $adminLogin = false;

    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct(Request $request)
    {
        $this->middleware('guest', ['except' => 'logout']);
        $path = $router = $request->route()->getPath();
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validatorRegister(array $data)
    {
        return Validator::make($data, [
            'mobile_phone' => 'required|max:11',
            //'mobile_phone' => 'required|unique:users|max:11',
        ]); 
    }

    protected function validatorLogin(array $data, $isWechat)
    {
        if($isWechat) {
            return Validator::make($data, [
                'mobile_phone' => 'required|max:11',
            ]);
        } else {
            return Validator::make($data, [
                'mobile_phone' => 'required|max:11',
                'password' => 'required'
            ]);
        }

    }

    /**
     * Handle a registration request for the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function register(Request $request)
    {
        $validator = $this->validatorRegister($request->all());

        if ($validator->fails()) {
            $this->throwValidationException(
                $request, $validator
            );
        }

        $result = $this->create($request->all());

        if ($result == 'no port user' || $result == 'leader') {
            return response($result);
        } else {
            Auth::guard($this->getGuard())->login($result);
            return response(Auth::user()->id);
        }
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    public  function create(array $data)
    {
        $sms_code = session('smscode');

        if ($sms_code != $data['smscode']) {
            response('bad injection', 500);
        }
        //取出open_id
        $user_info = session('user_info', array());
        $openid = isset($user_info['openid']) ? $user_info['openid'] : '';

        if($openid) {
            $phoneNumber = $data['mobile_phone'];
            $sugar = new \Spinegar\Sugar7Wrapper\Rest();
            $config = \App::make('config')->get('services.stm');
            extract($config);
            $sugar->setUrl($hosturl)
                ->setUsername($username)
                ->setPassword($password)
                ->setPlatform($platform)
                ->connect();

            $contacts = $sugar->filter('Contacts', array(
                'filter' => array(
                    array('phone_work' => $phoneNumber)
                )
            ));
            $account = array();
            $filterContacts = array();

            if (count($contacts['records'])) {
                foreach($contacts['records'] as $records) {
                    if ($records['is_portal_user_c'] == 1) {
                        $filterContacts[] = $records;
                    }
                }
            }

            if(count($contacts['records'])) {
                if(count($filterContacts) >= 2) {
                    foreach ($filterContacts as $key => $record) {
                        $contactsCreate[$key] = strtotime($record['date_entered']);
                    }
                    $minkey = array_search(min($contactsCreate),$contactsCreate);
                    $account = $filterContacts[$minkey];
                } elseif(count($filterContacts) ==0) {
                    $returnMessage = 'no port user';
                    return $returnMessage;
                } else {
                    $account = $filterContacts[0];
                }
                $model = 'Contacts';
            } else {
                $leaders = $sugar->filter('Leads', array(
                    'filter' => array(
                        array('phone_home' => $phoneNumber),
                    )
                ));
                if (count($leaders['records'])) {
                    if(count($leaders['records']) >= 2) {
                        foreach ($leaders['records'] as $key => $record) {
                            $leadsCreate[$key] = strtotime($record['date_entered']);
                        }
                        $minkey = array_search(min($leadsCreate),$leadsCreate);
                        $account = $leaders['records'][$minkey];
                    } else {
                        $account = $leaders['records'][0];
                    }
                }
                $model = 'Leads';
            }
            $base = array(
                'gender_c' => $user_info['sex'] ? ($user_info['sex'] == 1 ? 'male' : 'female') : '',
                'region_c' => $user_info['province'],
                'city_c'   => $user_info['city'],
                'open_id_c' => $user_info['openid'],
                'wechat_name_c' => $user_info['nickname'],
            );

            if ($model == 'Leads') {
                $base['lead_source'] = 'Wechat';
                $returnMessage = 'leader';
            }
            $request = request();
            $request->session()->forget('smscode');

            if ($account) {
                $status = $sugar->update($model, $account['id'], $base);
            } else {
                $base['first_name'] = $user_info['nickname'];
                $base['phone_home'] = $phoneNumber;
                $status = $sugar->create($model, $base);
            }

            if($status) {
                $user = User::where('mobile_phone', $phoneNumber)->where('openid', '')->first();
                if ($user) {
                    $user->name = $user_info['nickname'];
                    $user->gender = $user_info['sex'] ? ($user_info['sex'] == 1 ? 'male' : 'female') : '';
                    $user->openid = $user_info['openid'];
                    $user->mobile_phone = $phoneNumber;
                    $user->city = isset($user_info['city']) ? $user_info['city'] : '';
                    $user->region = isset($user_info['province']) ? $user_info['province'] : '';
                    $user->is_contact = ($model == 'Contacts') ? 1 : 0;
                    $user->save();
                } else {
                    $user = User::create([
                        'name' => $user_info['nickname'],
                        'gender' => $user_info['sex'] ? ($user_info['sex'] == 1 ? 'male' : 'female') : '',
                        'openid' => $user_info['openid'],
                        'mobile_phone' => $phoneNumber,
                        'city' => isset($user_info['city']) ? $user_info['city'] : '',
                        'region' => isset($user_info['province']) ? $user_info['province'] : '',
                        'is_contact' => ($model == 'Contacts') ? 1 : 0
                    ]);
                }

                $request->session()->forget('smscode_method');
            } else {
                $log = new Log;
                $log->title = 'register error: ' . $data['mobile_phone'];
                $log->save();
                abort(404);
            }
        }
        if (isset($returnMessage) && $returnMessage == 'leader') {
           return  $returnMessage;
        }
        return $user;
    }


    /**
     * Handle a login request to the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return 1 or 0
     */
    protected function login(Request $request, UserRepository $users) {
        $validator = $this->validatorLogin($request->all(), $request->session()->get('wechat'));

        if ($validator->fails()) {
            $this->throwValidationException(
                $request, $validator
            );
        }
        $request->session()->forget('smscode');

        $user = $users->getByPhone($request->input('mobile_phone'));

        if ($request->session()->get('wechat')) {
            if (!empty($user)) {
                Auth::login($user, true);
                return response()->json(Auth::user()->id);
            } else {
                return response()->json(0);
            }
        } else {
            $sugar = new \Spinegar\Sugar7Wrapper\Rest();
            $config = \App::make('config')->get('services.stm');
            extract($config);
            $sugar->setUrl($hosturl)
                ->setUsername($username)
                ->setPassword($password)
                ->setPlatform($platform)
                ->connect();

            $contacts = $sugar->filter('Contacts', array(
                'filter' => array(
                    array('phone_work' => $request->input('mobile_phone')),
                    array('password_c' => $request->input('password')),
                )
            ));

            if ($contacts['records']) {
                $records = $contacts['records'][0];
                if (!empty($user)) {
                    if($records['is_portal_user_c'] != 1) {
                        return response()->json('port fail');
                    }
                    $user->is_contact = 1;
                    $user->name = $records['wechat_name_c'];
                    $user->gender = $records['gender_c'];
                    $user->mobile_phone = $records['phone_work'];
                    $user->city = $records['city_c'];
                    $user->region = $records['region_c'];
                    $user->save();
                    Auth::login($user, true);
                    return response()->json(Auth::user()->id);
                } else {
                    $user = User::create([
                        'name' => $records['wechat_name_c'] ? $records['wechat_name_c'] : $records['name'],
                        'gender' => $records['gender_c'],
                        'openid' => '',
                        'mobile_phone' => $request->input('mobile_phone'),
                        'city' => $records['city_c'],
                        'region' => $records['region_c'],
                        'is_contact' => 1
                    ]);
                    if ($user) {
                        Auth::login($user, true);
                        return response()->json(Auth::user()->id);
                    } else {
                        return response()->json(0);
                    }
                }
            } else {
                return response()->json(0);
            }
        }
    }

    /**
     * Get the login username to be used by the controller.
     *
     * @return string
     */
    public function loginUsername()
    {
        return 'name';
    }

}

